package com.warm.xss.interceptor;

import com.warm.xss.utils.EscapeUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.PathRule;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

import java.util.Map;

@Condition(onProperty = "${xss.enabled:true} = true")
@Component
public class XssRouterInterceptor implements RouterInterceptor {

    @Inject("${xss.excludes}")
    private String[] excludes;

    @Inject("${xss.urlPatterns}")
    private String[] urlPatterns;


    /**
     * 路径匹配模式
     */
    @Override
    public PathRule pathPatterns() {
        PathRule pathRule = new PathRule();
        if (urlPatterns != null && urlPatterns.length > 0) {
            pathRule.include(urlPatterns);
        }
        if (excludes != null && excludes.length > 0) {
            pathRule.include(excludes);
        }
        return pathRule;
    }

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        if (mainHandler != null) {
            // 请求头
            for (Map.Entry<String, String> kv : ctx.headerMap().entrySet()) {
                // 处理Val
                kv.setValue(EscapeUtil.clean(kv.getValue()));
            }

            // 请求参数
            for (Map.Entry<String, String> kv : ctx.paramMap().entrySet()) {
                // 处理val
                kv.setValue(EscapeUtil.clean(kv.getValue()));
            }

            // 请求主体
            if (ctx.contentType() != null && ctx.contentType().contains("json")) {
                // 处理vaL
                ctx.bodyNew(EscapeUtil.clean(ctx.body()));
            }
        }

        chain.doIntercept(ctx, mainHandler);
    }

}